package com.ruoyi.system.outto.goods.impl;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qiniu.util.UrlUtils;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.ImgUntil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttrTemplateMapper;
import com.ruoyi.system.V2.gameAttr.mapper.GameAttributeMapper;
import com.ruoyi.system.V2.gameAttr.service.IGameAttributeService;
import com.ruoyi.system.V2.goodInfo.mapper.GoodsInfoImgMapper;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.interAttr.domain.InterAttr;
import com.ruoyi.system.interAttr.mapper.InterAttrMapper;
import com.ruoyi.system.model.domain.*;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.outto.core.MapUntils;
import com.ruoyi.system.outto.goods.MIKeJinShouAPI;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MKeJinShouApiImpl implements MIKeJinShouAPI {

    static String phone = "18537003990";
    static String account = "j2kcVUtJMTkMkqQ96NPievsGFDqnYehXysdRg6Iv";
    @Resource
    private IGameAttributeService gameAttributeService;
    @Resource
    InterAttrMapper interAttrMapper;
    @Resource
    private GameAttributeMapper gameAttributeMapper;
    @Resource
    private GoodsInfoImgMapper goodsInfoImgMapper;
    @Resource
    private ArtRecMapper artRecMapper;
    @Resource
    private GameAttrTemplateMapper gameAttrTemplateMapper;

    public static void main(String[] args) {

        getTokenNew(null);
//        send(phone);//发送验证码
//        login("7889376",phone);
//        getToken(null);
//        getCookie();
//        String s = null;
//        try {
//            s = upLoadImg(LCConstant.defaultImg);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        System.out.println(s);

//        GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto = new GoodsInfoAndAttrValueDto();
//        goodsInfoAndAttrValueDto.setTitle("标题");
//        goodsInfoAndAttrValueDto.setTitleImg(LCConstant.defaultImg);
//        publish(goodsInfoAndAttrValueDto);
//        SalePartner salePartner = new SalePartner();
//        salePartner.setSaleKey("Apxo85fHzxZGGehuyRD6bBI2N4yDODG754AmLFir");
//        String cookie = getCookie(salePartner);
//        String goods = getGoods("0264707021", cookie);
//        String upper = upper(goods, cookie);
//        System.out.println(upper);
    }

    private void builderServer(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map params, String server) {
        JSONObject serjsonObject = JSONObject.parseObject(server);
        //开始匹配一级区服
        String interServeReqs = serjsonObject.getString("interServeReqs");
        String qufuid = "";
        if (Objects.equals(goodsInfoAndAttrValueDto.getGameType(), "0")) {
            qufuid = goodsInfoAndAttrValueDto.getSystemId() + "" + goodsInfoAndAttrValueDto.getCarrierId() + "";
        } else {
            qufuid = goodsInfoAndAttrValueDto.getGroupId() + "";
        }
        if(goodsInfoAndAttrValueDto.getGameName().equals("火影忍者")){
            List<JSONObject> oneServer = JSONObject.parseArray(interServeReqs, JSONObject.class);

            for (JSONObject object : oneServer) {
                String ydServeId = object.getString("YdServeId");
                if (StringUtils.isNotEmpty(ydServeId)) {
                    ydServeId = ydServeId.replace(",", "").replace(" ", "");
                    if (Objects.equals(ydServeId, qufuid)) {
                        String twoServeStr = object.getString("interServerRes");
                        List<JSONObject> twoServer = JSONObject.parseArray(twoServeStr, JSONObject.class);
                        params.put("area_id", object.getString("id"));
                        for (JSONObject object2 : twoServer) {
                            if (StringUtils.isNotEmpty(object2.getString("YdServeId"))) {
                                ydServeId = object2.getString("YdServeId").replace(",", "").replace(" ", "");
                                if (ydServeId.equals(goodsInfoAndAttrValueDto.getGroupId().toString())) {
                                    params.put("server_id", object2.getString("id"));
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }else if(goodsInfoAndAttrValueDto.getGameName().equals("金铲铲之战")){
            List<JSONObject> oneServer = JSONObject.parseArray(interServeReqs, JSONObject.class);

            for (JSONObject object : oneServer) {
                String ydServeId = object.getString("YdServeId");
                if (StringUtils.isNotEmpty(ydServeId)) {
                    ydServeId = ydServeId.replace(",", "").replace(" ", "");
                    if (Objects.equals(ydServeId, qufuid)) {
                        String twoServeStr = object.getString("interServerRes");
                        List<JSONObject> twoServer = JSONObject.parseArray(twoServeStr, JSONObject.class);
                        params.put("area_id", object.getString("id"));
                        params.put("server_id", twoServer.get(0).getString("id"));
                    }
                }
            }
        }else if(goodsInfoAndAttrValueDto.getGameName().equals("英雄联盟(手游)")){
            List<JSONObject> oneServer = JSONObject.parseArray(interServeReqs, JSONObject.class);

            for (JSONObject object : oneServer) {
                String ydServeId = object.getString("YdServeId");
                if (StringUtils.isNotEmpty(ydServeId)) {
                    ydServeId = ydServeId.replace(",", "").replace(" ", "");
                    if (Objects.equals(ydServeId, qufuid)) {
                        String twoServeStr = object.getString("interServerRes");
                        List<JSONObject> twoServer = JSONObject.parseArray(twoServeStr, JSONObject.class);
                        params.put("area_id", object.getString("id"));
                        params.put("server_id", twoServer.get(0).getString("id"));
                    }
                }
            }
        }else if(goodsInfoAndAttrValueDto.getGameName().equals("暗区突围")){
            List<JSONObject> oneServer = JSONObject.parseArray(interServeReqs, JSONObject.class);

            for (JSONObject object : oneServer) {
                String ydServeId = object.getString("YdServeId");
                if (StringUtils.isNotEmpty(ydServeId)) {
                    ydServeId = ydServeId.replace(",", "").replace(" ", "");
                    if (Objects.equals(ydServeId, qufuid)) {
                        String twoServeStr = object.getString("interServerRes");
                        List<JSONObject> twoServer = JSONObject.parseArray(twoServeStr, JSONObject.class);
                        params.put("area_id", object.getString("id"));
                        params.put("server_id", twoServer.get(0).getString("id"));
                    }
                }
            }
        }else {
            List<JSONObject> oneServer = JSONObject.parseArray(interServeReqs, JSONObject.class);

            for (JSONObject object : oneServer) {
                String ydServeId = object.getString("YdServeId");
                if (StringUtils.isNotEmpty(ydServeId)) {
                    ydServeId = ydServeId.replace(",", "").replace(" ", "");
                    if (Objects.equals(ydServeId, qufuid)) {
                        String twoServeStr = object.getString("interServerRes");
                        List<JSONObject> twoServer = JSONObject.parseArray(twoServeStr, JSONObject.class);
                        params.put("area_id", object.getString("id"));
                        for (JSONObject object2 : twoServer) {
                            if (StringUtils.isNotEmpty(object2.getString("YdServeId"))) {
                                ydServeId = object2.getString("YdServeId").replace(",", "").replace(" ", "");
                                if (ydServeId.equals(goodsInfoAndAttrValueDto.getServerId().toString())) {
                                    params.put("server_id", object2.getString("id"));
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private void builderRadioAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map params, String radioAttr) {

        //========================开始匹配单选属性=====================//
        JSONObject jsonObject = JSONObject.parseObject(radioAttr);
        String interRadioReqs = jsonObject.getString("interRadioReqs");
        log.info(JSONObject.toJSONString(interRadioReqs));
        List<JSONObject> jsonObjects = JSONObject.parseArray(interRadioReqs, JSONObject.class);
        if (CollectionUtils.isEmpty(jsonObjects)) {
            throw new GlobalException("接口单选属性暂未配置");
        }
        /**
         * 1、先查询自定义中所有单选的字段
         * 2、再查该账号单选字段中的选项
         * 3、再去接口属性匹配表过滤
         */
        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        gameAttrTemplate.setFieldType("radio");
        List<GameAttrTemplate> gameAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();


        List<JSONObject> defObjects = new ArrayList<>();
        defObjects.addAll(jsonObjects);
        for (JSONObject object : jsonObjects) {
            for (GameAttrTemplate attrTemplate : gameAttrTemplates) {
                String aavName = attrTemplate.getAavName();
                for (Field declaredField : declaredFields) {
                    String name = declaredField.getName();
                    if (aavName.equals(name)) {
                        //一级属性
                        //注意 YdConfigId 对应的是 f字段对应的 id
                        if (Objects.equals(object.getLong("YdConfigId"), attrTemplate.getId())) {
                            String InterConfigId = object.getString("InterConfigId");
                            defObjects.remove(object);//如果匹配上，则去掉
                            String interRadioReqs1 = object.getString("interRadioReqs");
                            List<JSONObject> jsonObjects2 = JSONObject.parseArray(interRadioReqs1, JSONObject.class);
                            declaredField.setAccessible(true);
                            try {
                                //获取选择的值 例如  实名中的可二次
                                Object o = declaredField.get(goodsInfoAndAttrValueDto);
                                String oneValue = String.valueOf(o);
                                List<JSONObject> twoAttr = jsonObjects2.stream().filter(j -> StringUtils.isNotEmpty(j.getString("YdConfigId")) ? j.getString("YdConfigId").contains(oneValue) : "1".contains(oneValue)).collect(Collectors.toList());
                                String interConfigName = object.getString("InterConfigName");
                                String defaultValue = object.getString("defaultValue");
                                if (CollectionUtils.isEmpty(twoAttr)) {
                                    if (StringUtils.isNotEmpty(defaultValue)) {
                                        params.put(InterConfigId, defaultValue);
                                    }
                                }
                                if (!CollectionUtils.isEmpty(twoAttr)) {
                                    JSONObject jsonObject2 = twoAttr.get(0);
                                    String interConfigId2 = jsonObject2.getString("InterConfigId");
                                    params.put("property[" + InterConfigId + "]", interConfigId2);

                                }
                            } catch (Exception e) {
                                throw new GlobalException("单选项" + attrTemplate.getFieldName() + "匹配错误");
                            }
                        }
                    }
                }
            }
        }
        //开始匹配默认值
        for (JSONObject object : defObjects) {
            HashMap<String, Object> mateMap = new HashMap<>();
            String id = object.getString("id");
            String interRadioReqss = object.getString("interRadioReqs");
            List<JSONObject> jsonObjectss = JSONObject.parseArray(interRadioReqss, JSONObject.class);
            for (JSONObject jsonObject1 : jsonObjectss) {
                if (StringUtils.isNotEmpty(jsonObject1.getString("defaultValue"))) {
                    params.put("property[" + id + "]", jsonObject1.getString("defaultValue"));
                    break;
                }
            }
        }
        //========================单选属性匹配结束=====================//
    }

    private void builderCheckAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map params, String checkAttr) {
        //========================开始匹配多选属性=====================//
        /**
         * 1、先查询自定义中所有多选的字段
         * 2、再查该账号单选字段中的选项
         * 3、再去接口属性匹配表过滤
         */
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();
        JSONObject checkAttrJson = JSONObject.parseObject(checkAttr);
        String interCheckBoxReqs = checkAttrJson.getString("interCheckBoxReqs");
        List<JSONObject> checkJsonList = JSONObject.parseArray(interCheckBoxReqs, JSONObject.class);
        if (CollectionUtils.isEmpty(checkAttrJson)) {
            throw new GlobalException("接口多选属性暂未配置");
        }

        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        List<String> types = new ArrayList<>();
        types.add("checkbox");
        types.add("boxradio");
        gameAttrTemplate.setFieldTypes(types);
        List<GameAttrTemplate> checkAttrTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);

        for (JSONObject object : checkJsonList) {
            HashMap<String, Object> mateMap = new HashMap<>();
            String InterConfigId = object.getString("InterConfigId");
            List<String> list = new ArrayList<>();
            for (GameAttrTemplate attrTemplate : checkAttrTemplates) {
                String aavName = attrTemplate.getAavName();
                for (Field declaredField : declaredFields) {
                    String name = declaredField.getName();
                    if (aavName.equals(name)) {
                        declaredField.setAccessible(true);

                        String ydConfigIdLeveOne = object.getString("YdConfigId");
                        if (StringUtils.isNotEmpty(ydConfigIdLeveOne)) {

                            String[] split2 = ydConfigIdLeveOne.split(",");
                            List<String> list2 = new ArrayList<>();
                            for (String s : split2) {
                                s = s.replace(" ", "");
                                list2.add(s);
                            }
                            if (list2.contains(attrTemplate.getId() + "")) {
                                Object o = null;
                                try {
                                    o = declaredField.get(goodsInfoAndAttrValueDto);
                                } catch (IllegalAccessException e) {
                                    throw new GlobalException("多选项" + attrTemplate.getFieldName() + "匹配错误");
                                }
                                String oneValue = String.valueOf(o);
                                //一级属性
                                String ydConfigId = object.getString("YdConfigId");
                                String InterConfigName = object.getString("InterConfigName");
                                if (StringUtils.isNotEmpty(ydConfigId)) {
                                    ydConfigId = ydConfigId.replace(" ","");
                                    String[] split = ydConfigId.split(",");
                                    //一级属性已经匹配，开始匹配二级属性
                                    if (Arrays.asList(split).contains(attrTemplate.getId() + "")) {
                                        String interCheckBoxReqsStr = object.getString("interCheckBoxReqs");
//                                        String interCheckBoxReqsStr = object.getString("interServerRes");
                                        //开始匹配二级属性
                                        List<JSONObject> jsonObjects2 = JSONObject.parseArray(interCheckBoxReqsStr, JSONObject.class);
                                        /**
                                         * 咱们的f字段  多选项都是用空格 隔开，用,号切割数组，跟匹配的数据匹配、匹配上说明此账号勾选的有此属性
                                         */
                                        for (JSONObject jsonObject1 : jsonObjects2) {
                                            if (StringUtils.isNotEmpty(oneValue)) {
                                                String[] split1 = oneValue.split(",");
                                                String ydConfigId1 = jsonObject1.getString("YdConfigId");
                                                if (StringUtils.isNotEmpty(ydConfigId1)) {
                                                    ydConfigId1 = ydConfigId1.replace(" ", "");
                                                    for (String s : split1) {
                                                        if (Objects.equals(s, ydConfigId1)) {
                                                            String InterConfigId2 = jsonObject1.getString("InterConfigId");
                                                            list.add(InterConfigId2);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    throw new GlobalException("属性参数错误，请匹配后重新配置");
                                }
                            }
                        }
                    }
                }
            }
            if (!CollectionUtils.isEmpty(list)) {
                params.put("property[" + InterConfigId + "][]", list);
            }
        }
        //========================多选属性匹配完成=====================//
    }

    private void builderInputAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map params, String inputAttr) {
        Field[] declaredFields = goodsInfoAndAttrValueDto.getClass().getDeclaredFields();

        //========================开始匹配输入框=====================//
        JSONObject jsonObject1 = JSONObject.parseObject(inputAttr);
        String inputJson = jsonObject1.getString("inputJson");
        List<JSONObject> jsonObjects1 = JSONObject.parseArray(inputJson, JSONObject.class);
        GameAttrTemplate gameAttrTemplate = new GameAttrTemplate();
        gameAttrTemplate.setGameId(goodsInfoAndAttrValueDto.getGameId());
        gameAttrTemplate.setIsEnable("0");
        ArrayList types = new ArrayList<>();
        types.add("number");
        types.add("input");
        gameAttrTemplate.setFieldTypes(types);
        List<GameAttrTemplate> inputTemplates = gameAttrTemplateMapper.selectGameAttrTemplateList(gameAttrTemplate);
        List<JSONObject> defInputObjects = new ArrayList<>();
        defInputObjects.addAll(jsonObjects1);
        for (JSONObject object : jsonObjects1) {
            for (GameAttrTemplate inputTemplate : inputTemplates) {
                String aavName = inputTemplate.getAavName();
                if (Objects.equals(object.getString("aavName"), inputTemplate.getAavName())) {
                    defInputObjects.remove(object);
                    String aavNameInter = object.getString("interName");
                    String interId = object.getString("interId");
                    for (Field declaredField : declaredFields) {
                        String name = declaredField.getName();
                        if (Objects.equals(aavName, name)) {
                            declaredField.setAccessible(true);
                            String oneValue = null;
                            try {
                                oneValue = (String) declaredField.get(goodsInfoAndAttrValueDto);
                            } catch (IllegalAccessException e) {
                                throw new GlobalException("3属性参数错误，请匹配后重新配置");
                            }
                            if (StringUtils.isNotEmpty(oneValue)) {
                                params.put("property[" + interId + "]", oneValue);
                            }
                        }
                    }
                }

            }
        }
        //开始匹配默认值
        for (JSONObject object : defInputObjects) {
            String id = object.getString("id");
            String defaultValue = object.getString("defaultValue");
            if (StringUtils.isNotEmpty(defaultValue)) {
                if(object.getString("name").contains("亮点")){
                    params.put("property[" + id + "]", goodsInfoAndAttrValueDto.getTitle());
                }else {
                    params.put("property[" + id + "]", 0);
                }
            }
        }
    }

    private String params(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, InterAttr interAttr, SalePartner salePartner) {
        Map<String, Object> params = new TreeMap<>();
        if (1 == 1) {
            params.put("_token", getToken(salePartner));

            params.put("game_id", interAttr.getInterGameId());
            params.put("title", goodsInfoAndAttrValueDto.getTitle());
            params.put("game_account", goodsInfoAndAttrValueDto.getAccountNumber());
            params.put("game_pwd", String.valueOf(System.currentTimeMillis()).substring(3));
            params.put("price", Math.ceil(goodsInfoAndAttrValueDto.getPrice().doubleValue()));

            //开始匹配区服属性
            if (goodsInfoAndAttrValueDto.getGameName().equals("永劫无间")) {
                if (goodsInfoAndAttrValueDto.getGroupName().equals("网易")) {
                    if (goodsInfoAndAttrValueDto.getServerName().contains("手机")) {
                        params.put("area_id", "48");
                        params.put("server_id", "8123");
                    } else {
                        params.put("area_id", "49");
                        params.put("server_id", "8124");
                    }
                } else if (goodsInfoAndAttrValueDto.getGroupName().equals("Steam")) {
                    params.put("area_id", "299");
                    params.put("server_id", "8125");
                } else {
                    params.put("area_id", "453");
                    params.put("server_id", "8126");
                }
            } else  if (goodsInfoAndAttrValueDto.getGameName().equals("永劫无间手游")) {
                if (goodsInfoAndAttrValueDto.getCarrierName().contains("手机")) {
                    params.put("area_id", "6970");
                    params.put("server_id", "8824");
                } else {
                    params.put("area_id", "8017");
                    params.put("server_id", "8825");
                }
            } else  if (goodsInfoAndAttrValueDto.getGameName().equals("使命召唤手游")) {
                String regional = goodsInfoAndAttrValueDto.getSystemName()+goodsInfoAndAttrValueDto.getCarrierName();
                if (regional.contains("安卓QQ")) {
                    params.put("area_id", "386");
                    params.put("server_id", "1781");
                } else if (regional.contains("安卓微信")) {
                    params.put("area_id", "387");
                    params.put("server_id", "1782");
                } else if (regional.contains("苹果QQ")) {
                    params.put("area_id", "388");
                    params.put("server_id", "1783");
                } else {
                    params.put("area_id", "389");
                    params.put("server_id", "1784");
                }
            } else {
                builderServer(goodsInfoAndAttrValueDto, params, interAttr.getServer());
            }
            //开始匹配单选属性
            builderRadioAttr(goodsInfoAndAttrValueDto, params, interAttr.getRadioAttr());
            //开始匹配多选属性
            builderCheckAttr(goodsInfoAndAttrValueDto, params, interAttr.getCheckAttr());
            //开始匹配输入框属性
            builderInputAttr(goodsInfoAndAttrValueDto, params, interAttr.getInputAttr());


            params.put("attr_type", "normal");

            List<GoodsInfoImg> infoImgs = new ArrayList<>();
            String zhutuId = "";
            String xiangqingtuId = "";
            if (goodsInfoAndAttrValueDto.getGameName().equals("王者荣耀")) {
                params.put("property[18]", goodsInfoAndAttrValueDto.getTitle());
                zhutuId = "1452";
                xiangqingtuId = "48";
            } else if (goodsInfoAndAttrValueDto.getGameName().equals("永劫无间")) {
                zhutuId = "1498";
                xiangqingtuId = "95";
            } else if (goodsInfoAndAttrValueDto.getGameName().equals("和平精英")) {
                zhutuId = "1458";
                xiangqingtuId = "277";
            } else if(goodsInfoAndAttrValueDto.getGameName().equals("穿越火线")){
                zhutuId = "203";
                xiangqingtuId = "201";
            }else if(goodsInfoAndAttrValueDto.getGameName().equals("火影忍者")){
                zhutuId = "485";
                xiangqingtuId = "217";
            }else if(goodsInfoAndAttrValueDto.getGameName().equals("金铲铲之战")){
                zhutuId = "5475";
                xiangqingtuId = "255";
            }else if(goodsInfoAndAttrValueDto.getGameName().equals("英雄联盟")){
                zhutuId = "1496";
                xiangqingtuId = "47";
            }else if(goodsInfoAndAttrValueDto.getGameName().equals("枪战王者")){
                zhutuId = "488";
                xiangqingtuId = "245";
            }else if(goodsInfoAndAttrValueDto.getGameName().equals("永劫无间手游")){
                zhutuId = "5115";
                xiangqingtuId = "4151";
            }else if(goodsInfoAndAttrValueDto.getGameName().equals("英雄联盟(手游)")){
                zhutuId = "5341";
                xiangqingtuId = "252";
            }else if(goodsInfoAndAttrValueDto.getGameName().equals("暗区突围")){
                zhutuId = "";
                xiangqingtuId = "399";
            }else if(goodsInfoAndAttrValueDto.getGameName().equals("三角洲行动")){
                zhutuId = "5779";
                xiangqingtuId = "4668";
            }else if(goodsInfoAndAttrValueDto.getGameName().equals("使命召唤手游")){
                xiangqingtuId = "539";
            }
            String s1 = upLoadImg(goodsInfoAndAttrValueDto.getTitleImg(),salePartner);
            String data = JSONObject.parseObject(s1).getString("data");
            String url = JSONObject.parseObject(data).getString("url");
            Object o = JSONArray.parseArray(url).get(0);
            if(StringUtils.isNotEmpty(zhutuId)) {
                params.put("property[" + zhutuId + "][]", o.toString());
                params.put("back_url", "https://kejinlianmeng.com/account/goods/index?_pjax=%23main&game_id=1&status=4");
            }
            GoodsInfoImg goodsInfoImg = new GoodsInfoImg();
            goodsInfoImg.setGoodsId(goodsInfoAndAttrValueDto.getId());
            goodsInfoImg.setType(Constants.STR_1);
            infoImgs = goodsInfoImgMapper.selectGoodsInfoImgList(goodsInfoImg);

            String cover = getCover(params, infoImgs, xiangqingtuId,salePartner);
            cover = "_token=" + getToken(salePartner) + "&" + UrlUtils.urlEncode(cover);
            System.out.println(cover);
            return cover;
        }
        return null;
    }

    private List<GameAttribute> getGameAttributs(String ids) {
        if (StringUtils.isEmpty(ids)) {
            return new ArrayList<>();
        }
        return gameAttributeMapper.selectGameAttributeListByIds((Long[]) ConvertUtils.convert(ids.split(","),
                Long.class));
    }

    private String reIds(String allIds, String ids) {
        if (StringUtils.isNotEmpty(ids)) {
            if (StringUtils.isNotEmpty(allIds)) {
                allIds = allIds + "," + ids;
            } else {
                allIds = ids;
            }
        }
        return allIds;
    }

    public static String getGoods(String account, String gameId, String cookie) {
        String url = "https://kejinlianmeng.com/account/goods/index?game_id=" + gameId + "&status=0&id=&keyword=&tpg_id=&game_account=" + account;
        String result = HttpRequest.get(url).header("Accept", "*/*")
                .header("Accept-Language", "zh-CN,zh;q=0.9")
                .header("Cache-Control", "no-cache")
                .header("Connection", "keep-alive")
                .header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                .header("Cookie", cookie)
                .header("Origin", "https://kejinlianmeng.com")
                .header("Pragma", "no-cache")
                .header("Referer", "https://kejinlianmeng.com/account/goods/establish?game_id=1&back_url=https%3A%2F%2Fkejinlianmeng.com%2Faccount%2Fgoods%2Findex%3F_pjax%3D%2523main%26game_id%3D1")
                .header("Sec-Fetch-Dest", "empty")
                .header("Sec-Fetch-Mode", "cors")
                .header("Sec-Fetch-Site", "same-origin")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36")
                .header("X-Requested-With", "XMLHttpRequest")
                .header("sec-ch-ua", "\"Google Chrome\";v=\"129\", \"Not=A?Brand\";v=\"8\", \"Chromium\";v=\"129\"")
                .header("sec-ch-ua-mobile", "?0")
                .header("sec-ch-ua-platform", "\"Windows\"")
                .execute()
                .body();
        Document doc = Jsoup.parse(result);
        Element p = doc.select("tbody").first();
        String text = p.text().split(" ")[0].trim();
        return text;
    }

    public static String upper(String goodId, String cookie) {
        String url = "https://kejinlianmeng.com/account/goods/upper/" + goodId;
        String result = HttpRequest.post(url)
                .header("Accept", "*/*")
                .header("Accept-Language", "zh-CN,zh;q=0.9")
                .header("Cache-Control", "no-cache")
                .header("Connection", "keep-alive")
                .header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                .header("Cookie", cookie)
                .header("Origin", "https://kejinlianmeng.com")
                .header("Pragma", "no-cache")
                .header("Referer", "https://kejinlianmeng.com/account/goods/establish?game_id=1&back_url=https%3A%2F%2Fkejinlianmeng.com%2Faccount%2Fgoods%2Findex%3F_pjax%3D%2523main%26game_id%3D1")
                .header("Sec-Fetch-Dest", "empty")
                .header("Sec-Fetch-Mode", "cors")
                .header("Sec-Fetch-Site", "same-origin")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36")
                .header("X-Requested-With", "XMLHttpRequest")
                .header("sec-ch-ua", "\"Google Chrome\";v=\"129\", \"Not=A?Brand\";v=\"8\", \"Chromium\";v=\"129\"")
                .header("sec-ch-ua-mobile", "?0")
                .header("sec-ch-ua-platform", "\"Windows\"")
                .execute()
                .body();
        return result;
    }

    @Override
    public AjaxResult addGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {

        //属性匹配
        String substring = salePartner.getSaleName().substring(salePartner.getSaleName().indexOf("_") + 1);
        InterAttr interAttr = interAttrMapper.selectInterAttrByConfig(substring, goodsInfoAndAttrValueDto.getGameId());
        if (StringUtils.isEmpty(interAttr.getInterGameId())) {
            throw new GlobalException("该游戏属性暂未匹配!!!" + goodsInfoAndAttrValueDto.getGameName());
        }

        Map<String, Object> resultMap = new HashMap<>();
        String params = params(goodsInfoAndAttrValueDto, interAttr, salePartner);
        log.info("氪金兽添加接口请求参数={}", JSONObject.toJSONString(params));
        String cookie = getCookie(salePartner);
        String url = "https://kejinlianmeng.com/account/goods/establish/";
        String result = HttpRequest.post(url)
                .body(params)
                .header("Accept", "*/*")
                .header("Accept-Language", "zh-CN,zh;q=0.9")
                .header("Cache-Control", "no-cache")
                .header("Connection", "keep-alive")
                .header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                .header("Cookie", cookie)
                .header("Origin", "https://kejinlianmeng.com")
                .header("Pragma", "no-cache")
                .header("Referer", "https://kejinlianmeng.com/account/goods/establish?game_id=1&back_url=https%3A%2F%2Fkejinlianmeng.com%2Faccount%2Fgoods%2Findex%3F_pjax%3D%2523main%26game_id%3D1")
                .header("Sec-Fetch-Dest", "empty")
                .header("Sec-Fetch-Mode", "cors")
                .header("Sec-Fetch-Site", "same-origin")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36")
                .header("X-Requested-With", "XMLHttpRequest")
                .header("sec-ch-ua", "\"Google Chrome\";v=\"129\", \"Not=A?Brand\";v=\"8\", \"Chromium\";v=\"129\"")
                .header("sec-ch-ua-mobile", "?0")
                .header("sec-ch-ua-platform", "\"Windows\"")
                .execute()
                .body();

        //根据账号查询商品ID
        String goods = getGoods(goodsInfoAndAttrValueDto.getAccountNumber(), interAttr.getInterGameId(), cookie);

        log.info("氪金兽添加接口返回参数={}", result);
        System.out.println(MapUntils.unicodeToString(result));
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!"0".equals(resultJson.getString("status"))) {
            resultMap.put("code", 500);
        } else {
            resultMap.put("code", 200);
            resultMap.put("outId", goods);
            //上架
            upper(goods, cookie);
        }
        resultMap.put("req", JSONObject.toJSONString(params));
        resultMap.put("res", result);
        resultMap.put("msg", resultJson.getString("data"));

        return AjaxResult.success(resultMap);
    }

    @Override
    public AjaxResult editGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        //属性匹配
        String substring = salePartner.getSaleName().substring(salePartner.getSaleName().indexOf("_") + 1);
        InterAttr interAttr = interAttrMapper.selectInterAttrByConfig(substring, goodsInfoAndAttrValueDto.getGameId());
        if (StringUtils.isEmpty(interAttr.getInterGameId())) {
            throw new GlobalException("该游戏属性暂未匹配!!!" + goodsInfoAndAttrValueDto.getGameName());
        }
        Map<String, Object> resultMap = new HashMap<>();
        String params = params(goodsInfoAndAttrValueDto, interAttr, salePartner);
        log.info("氪金兽添加接口请求参数={}", JSONObject.toJSONString(params));
        String cookie = getCookie(salePartner);
        ArtRec artRecreq = new ArtRec();
        artRecreq.setConfig(salePartner.getId());
        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
        String url = "https://kejinlianmeng.com/account/goods/establish/" + artRecs.get(0).getOutid();
        String result = HttpRequest.post(url)
                .body(params)
                .header("Accept", "*/*")
                .header("Accept-Language", "zh-CN,zh;q=0.9")
                .header("Cache-Control", "no-cache")
                .header("Connection", "keep-alive")
                .header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                .header("Cookie", cookie)
                .header("Origin", "https://kejinlianmeng.com")
                .header("Pragma", "no-cache")
                .header("Referer", "https://kejinlianmeng.com/account/goods/establish?game_id=1&back_url=https%3A%2F%2Fkejinlianmeng.com%2Faccount%2Fgoods%2Findex%3F_pjax%3D%2523main%26game_id%3D1")
                .header("Sec-Fetch-Dest", "empty")
                .header("Sec-Fetch-Mode", "cors")
                .header("Sec-Fetch-Site", "same-origin")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36")
                .header("X-Requested-With", "XMLHttpRequest")
                .header("sec-ch-ua", "\"Google Chrome\";v=\"129\", \"Not=A?Brand\";v=\"8\", \"Chromium\";v=\"129\"")
                .header("sec-ch-ua-mobile", "?0")
                .header("sec-ch-ua-platform", "\"Windows\"")
                .execute()
                .body();
        JSONObject resultJson = JSONObject.parseObject(result);
        System.out.println(MapUntils.unicodeToString(result));
        if (!"0".equals(resultJson.getString("status"))) {
            resultMap.put("code", 500);
        } else {
            resultMap.put("code", 200);
        }
        resultMap.put("req", JSONObject.toJSONString(params));
        resultMap.put("res", result);
        resultMap.put("msg", resultJson.getString("data"));
        return AjaxResult.success(resultMap);
    }

    @Override
    public AjaxResult delGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> resultMap = new HashMap<>();
        ArtRec artRecreq = new ArtRec();
        artRecreq.setConfig(salePartner.getId());
        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
        ArtRec artRec = artRecs.get(0);
        String url = "https://kejinlianmeng.com/account/goods/under/" + artRec.getOutid();
        String result = HttpRequest.post(url)
                .header("Accept", "*/*")
                .header("Accept-Language", "zh-CN,zh;q=0.9")
                .header("Cache-Control", "no-cache")
                .header("Connection", "keep-alive")
                .header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                .header("Cookie", getCookie(salePartner))
                .header("Origin", "https://kejinlianmeng.com")
                .header("Pragma", "no-cache")
                .header("Referer", "https://kejinlianmeng.com/account/goods/establish?game_id=1&back_url=https%3A%2F%2Fkejinlianmeng.com%2Faccount%2Fgoods%2Findex%3F_pjax%3D%2523main%26game_id%3D1")
                .header("Sec-Fetch-Dest", "empty")
                .header("Sec-Fetch-Mode", "cors")
                .header("Sec-Fetch-Site", "same-origin")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36")
                .header("X-Requested-With", "XMLHttpRequest")
                .header("sec-ch-ua", "\"Google Chrome\";v=\"129\", \"Not=A?Brand\";v=\"8\", \"Chromium\";v=\"129\"")
                .header("sec-ch-ua-mobile", "?0")
                .header("sec-ch-ua-platform", "\"Windows\"")
                .execute()
                .body();
        log.info("氪金兽删除接口返回参数={}", MapUntils.unicodeToString(result));
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!"0".equals(resultJson.getString("status"))) {
            resultMap.put("code", 500);
        } else {
            resultMap.put("code", 200);
        }
        resultMap.put("req", JSONObject.toJSONString(artRec.getOutid()));
        resultMap.put("res", resultMap);
        resultMap.put("msg", resultMap);
        return AjaxResult.success(resultMap);
    }


    private static String getTokenNew(SalePartner salePartner) {
        String cookie = "account=" + account + "; _ga=GA1.1.2133416559.1726621808; acw_tc=ac11000117266272807932614e00e00608a859cf72b9d0f1ed3cb79246450c; _ga_TJJQCLLECR=GS1.1.1726627284.2.0.1726627284.0.0.0";

        String push = "https://kejinlianmeng.com/panel";
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2tlamlubGlhbm1lbmcuY29tL2FwaV92MS9zeXN0ZW0vYXV0aC9sb2dpbiIsImlhdCI6MTcyNjcxNjYyMSwiZXhwIjoxNzI5MzA4NjIxLCJuYmYiOjE3MjY3MTY2MjEsImp0aSI6Ijh4eURpRXQ1Nk5tWGp0ejEiLCJzdWIiOjE0NywicHJ2IjoiNjdkMzEwNjAzOTdkZWJkNDIyMzYzMWMxMTc1NGNlMTRjNjYzNDJjMSIsInVzZXIiOnsidHlwZSI6InVzZXIiLCJzYWx0IjoiOTg2YzBiY2U4MjQ5NGYyODM2NzM3ZDdlZTEzMjc4NDAifX0.kqQwbHUDDdL4_rbMvUL5yPFi--yDpMSbQDlJRE4_3Fs";

//        SalePartner salePartner = new SalePartner();
//        salePartner.setSaleKey("Y2QiXLIkakWFysiWl6xIev23MdQMe809OXWvzfdZ");


        String body = HttpRequest.get(push)
                .header("Cookie", getCookie(salePartner) + "remember_web_59ba36addc2b2f9401580f014c7f58ea4e30989d=" + token)
                .header("x-requested-with", "XMLHttpRequest")
                .execute()
                .body();
        Document parse = Jsoup.parse(body);

        Elements scripts = parse.select("script");
        for (Element script : scripts) {


            if (script.data().contains("wss://kejinlianmeng.com")) {
                String[] split = script.data().split("wss://kejinlianmeng.com");
                String[] split1 = split[1].split("let noticeCenter = new NoticeCenter");
                String s = split1[0];
                String replace = s.replace("/user';", "");
                replace = replace.replace(" ", "").replace("lettoken=","").replace("'","").replace(";","");
                return replace;
            }
        }

        return null;
    }


    private static String getToken(SalePartner salePartner) {
        String cookie = "account=" + account + "; _ga=GA1.1.2133416559.1726621808; acw_tc=ac11000117266272807932614e00e00608a859cf72b9d0f1ed3cb79246450c; _ga_TJJQCLLECR=GS1.1.1726627284.2.0.1726627284.0.0.0";

        String push = "https://kejinlianmeng.com/account/goods/establish?game_id=1&back_url=https%3A%2F%2Fkejinlianmeng.com%2Faccount%2Fgoods%2Findex%3F_pjax%3D%2523main%26game_id%3D1&_pjax=%23main";
//        String push = "https://kejinlianmeng.com/account/dashboard/good_num";
//            Document document = Jsoup.connect(push)
//                    .header("cookie","remember_web=eyJpdiI6ImxYM3dlVGxxbTVuWEJTNklXalZoM1E9PSIsInZhbHVlIjoiemhiY0h1MkF2U0hZUlo3eDVJbURkMHA1ZWNiR0l1MVRsNW1kQkFwUlZzcGw5S0NEWFRjUlhSU0R6blo5VkFqQWFEZllPUDNrd1dlUFNJVzZIakdqM1JiaEFmU0FSckEzOFwvRXQybTc1clBKWllVOVhzVnJnaWRsdHptcktvXC9ZSTdLOG01YjJ3M2ZXd2RqTmhpNkdFazE4TXhWdjJibCtOajdlZTFIb2xKWjJlNjV0UVhhNFpIem9MdkVLRTJSRXoiLCJtYWMiOiI1ZjA2MGQ4OTk2YWI3Yzk2NzVmOGM5NmE5N2NmMjQxYzBlNzQwMjM0M2MyM2Q4YmJiMTUwNTg1ZjQzNWQyYTcwIn0%3D")
//                    .header("x-requested-with","XMLHttpRequest")
//                    .get();
//        SalePartner salePartner = new SalePartner();
//        salePartner.setSaleKey("Apxo85fHzxZGGehuyRD6bBI2N4yDODG754AmLFir");
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL2tlamlubGlhbm1lbmcuY29tL2FwaV92MS9zeXN0ZW0vYXV0aC9sb2dpbiIsImlhdCI6MTcyNjcxNjYyMSwiZXhwIjoxNzI5MzA4NjIxLCJuYmYiOjE3MjY3MTY2MjEsImp0aSI6Ijh4eURpRXQ1Nk5tWGp0ejEiLCJzdWIiOjE0NywicHJ2IjoiNjdkMzEwNjAzOTdkZWJkNDIyMzYzMWMxMTc1NGNlMTRjNjYzNDJjMSIsInVzZXIiOnsidHlwZSI6InVzZXIiLCJzYWx0IjoiOTg2YzBiY2U4MjQ5NGYyODM2NzM3ZDdlZTEzMjc4NDAifX0.kqQwbHUDDdL4_rbMvUL5yPFi--yDpMSbQDlJRE4_3Fs";
        String body = HttpRequest.get(push)
                .header("Cookie", getCookie(salePartner) + "remember_web_59ba36addc2b2f9401580f014c7f58ea4e30989d=" + token)
                .header("x-requested-with", "XMLHttpRequest")
                .execute()
                .body();
        Document parse = Jsoup.parse(body);
        Elements metaTags = parse.select("meta");
        String content = metaTags.last().attr("content");
        log.info("content={}", content);
        return content;
    }

    private static String getCookie(SalePartner salePartner) {

//        String s = new Date().getTime() / 1000 + "";

        String cookie = "account=" + salePartner.getSaleKey() + "; _ga=GA1.1.2133416559.1726621808; acw_tc=ac11000117266272807932614e00e00608a859cf72b9d0f1ed3cb79246450c; _ga_TJJQCLLECR=GS1.1.1726627284.2.0.1726627284.0.0.0";
        return cookie;
    }

    private static void publish(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto) {
//        String s = upLoadImg(LCConstant.defaultImg);
//        System.out.println(s);
        String send = "https://kejinlianmeng.com/account/goods/establish";

        TreeMap params = new TreeMap();
//        String token = getToken();
        params.put("_token", "hTQqxuxIR3V9m878doLHVhuvAEaIPyKWG4Ixz5va");

        params.put("game_id", 1);
        params.put("title", goodsInfoAndAttrValueDto.getTitle());
        params.put("area_id", 2);
        params.put("server_id", 6);
        params.put("game_account", String.valueOf(System.currentTimeMillis()).substring(3));
        params.put("game_pwd", String.valueOf(System.currentTimeMillis()).substring(3));
        params.put("price", 1000);
        String s1 = upLoadImg(goodsInfoAndAttrValueDto.getTitleImg(),null);
        String data = JSONObject.parseObject(s1).getString("data");
        String url = JSONObject.parseObject(data).getString("url");
        Object o = JSONArray.parseArray(url).get(0);
        params.put("property[1452][]", o.toString());
        params.put("property[1454][]", o.toString());

        params.put("property[1518]", 18464);
        params.put("property[12]", 1102);
        params.put("property[29]", 176);
        params.put("property[20]", 12);
        params.put("property[6]", 75695571);
        params.put("property[5]", 119);
        params.put("property[4]", 119);
        params.put("property[7]", 1);
        params.put("property[9]", 5);
        params.put("property[5109]", 37776);
        params.put("property[2311]", 23838);
        params.put("property[426]", 4550);
        params.put("property[26][]", 25906);
        params.put("property[26][]", 29262);
        params.put("property[26][]", 20);
        params.put("property[18]", "可认证安卓（q）区119皮4传说42限定7王者印记.亮点：乘龙-问璇玑 冠军飞将 凤求凰 地狱火 水晶猎龙者 大圣娶亲 【道具：318亲密玫瑰 26浓情玫瑰 】qj");
        params.put("attr_type", "normal");
        params.put("back_url", "https://kejinlianmeng.com/account/goods/index?_pjax=%23main&game_id=1&status=4");

        String cover = getCover(params, null, null,null);
//        System.out.println(cover);

//        JSONObject jsonObject = new JSONObject(params);
//        String s3 = "_token=hTQqxuxIR3V9m878doLHVhuvAEaIPyKWG4Ixz5va&game_id=1&title=8%E5%B8%A6%E7%81%B5%E5%AE%9D%2F245%E7%9A%AE%E8%82%A4%2F2%E5%85%B8%E8%97%8F%2F18%E4%BC%A0%E8%AF%B4%2F88%E9%99%90%E5%AE%9A%2F2%E6%98%9F%E4%BC%A0%E8%AF%B4%E6%9C%AB%E6%97%A5%E6%9C%BA%E7%94%B2%2F%E8%B6%85%E6%97%B6%E7%A9%BA%E6%88%98%E5%A3%AB%2F14%E5%8D%B0%E8%AE%B0121%E8%8B%B1%E9%9B%84%2F%E5%B0%8F%E4%B9%94-%E5%A4%A9%E9%B9%85%E4%B9%8B%E6%A2%A6+%E5%A4%8F%E4%BE%AF%E6%83%87-%E6%97%A0%E9%99%90%E9%A3%93%E9%A3%8E%E5%8F%B7%2F%E6%BE%9C-%E9%80%90%E8%8A%B1%E5%BD%92%E6%B5%B7+%E5%90%95%E5%B8%83-%E5%A4%A9%E9%AD%94%E7%BC%AD%E4%B9%B1+%E7%8B%84%E4%BB%81%E6%9D%B0-%E8%B6%85%E6%97%B6%E7%A9%BA%E6%88%98%E5%A3%AB+%E4%BC%BD%E7%BD%97-%E5%A4%AA%E5%8D%8E+%E5%B9%B2%E5%B0%86%E8%8E%AB%E9%82%AA-%E4%B9%85%E8%83%9C%E6%88%98%E7%A5%9E+%E5%85%AC%E5%AD%99%E7%A6%BB-%E7%A5%88%E9%9B%AA%E7%81%B5%E7%A5%9D+%E5%90%8E%E7%BE%BF-%E9%BB%84%E9%87%91&area_id=4&server_id=8&source_id=&game_account=2984105427&game_pwd=&game_nickname=&account_bind_mobile=&amount=&price=1000&property%5B1062%5D=33514&property%5B6%5D=454052437&property%5B5%5D=&property%5B16%5D=&property%5B4%5D=&property%5B14%5D=&property%5B19%5D=&property%5B8%5D=&property%5B12%5D=1102&property%5B1518%5D=18464&property%5B9%5D=5&image=&property%5B1452%5D%5B%5D=https%3A%2F%2Ffile.kejinlianmeng.com%2Ftemp%2F202410%2F23%2F15%2F1325eifPZB2y.jpg&image=&property%5B48%5D%5B%5D=https%3A%2F%2Ffile.kejinlianmeng.com%2Ftemp%2F202410%2F23%2F15%2F132934tVEmBH.jpg&image=&property%5B18%5D=&image=&image=&image=&image=&image=&xs_platform=&attr_type=normal&back_url=https%3A%2F%2Fkejinlianmeng.com%2Faccount%2Fgoods%2Findex%3F_pjax%3D%2523main%26game_id%3D1&is_tool=";
//        System.out.println(s3);
        String body = HttpRequest.post("https://kejinlianmeng.com/account/goods/establish")
                .body(cover)
                .header("Accept", "*/*")
                .header("Accept-Language", "zh-CN,zh;q=0.9")
                .header("Cache-Control", "no-cache")
                .header("Connection", "keep-alive")
                .header("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                .header("Cookie", "_ga=GA1.1.1278412161.1681543055; account=Apxo85fHzxZGGehuyRD6bBI2N4yDODG754AmLFir; remember_web_59ba36addc2b2f9401580f014c7f58ea4e30989d=eyJpdiI6IjlVQWp4dVZDeGlmWkxLYUJCVkVsd2c9PSIsInZhbHVlIjoiRit1ZlVLRTRGN3gwR0RVeEFLQmY1VHgzTWQ2UlpkQ2RoZ3BmN0pvXC9aRks1WGNuK1poOGZqQnVOOERReENMSmRBaU5OVDBiSVBBMjJFT1wvcGQwZFFSeUs2MUtGZjdVZndDMU0rQ21DK0NpYmVjZ3h4eHE5aHJaaFBOYis0dUFcL0kwVUplem1UeURTc2pwR05JT3VhNWxJdzlSYlh2T0pcL2RxUEw5bGdoc1BacjlzNXdSTnN3R1lmNnNpa2VxOXZVciIsIm1hYyI6ImM3Y2ZlMTI1NThjMjMwNzUyZjFjMzE5Yjc2NTJiMTFiOTVkYWNlYWQ2MWIyNDJhNGU4ZjFkZDA4YTJjZjQ2ZWMifQ%3D%3D; _ga_TJJQCLLECR=GS1.1.1729667463.27.1.1729667522.0.0.0; account=Apxo85fHzxZGGehuyRD6bBI2N4yDODG754AmLFir")
                .header("Origin", "https://kejinlianmeng.com")
                .header("Pragma", "no-cache")
                .header("Referer", "https://kejinlianmeng.com/account/goods/establish?game_id=1&back_url=https%3A%2F%2Fkejinlianmeng.com%2Faccount%2Fgoods%2Findex%3F_pjax%3D%2523main%26game_id%3D1")
                .header("Sec-Fetch-Dest", "empty")
                .header("Sec-Fetch-Mode", "cors")
                .header("Sec-Fetch-Site", "same-origin")
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36")
                .header("X-Requested-With", "XMLHttpRequest")
                .header("sec-ch-ua", "\"Google Chrome\";v=\"129\", \"Not=A?Brand\";v=\"8\", \"Chromium\";v=\"129\"")
                .header("sec-ch-ua-mobile", "?0")
                .header("sec-ch-ua-platform", "\"Windows\"")
                .execute()
                .body();
//        log.info("验证码发送结果={}", body);
    }

    /**
     * 发送验证码
     *
     * @return
     */
    private static void send(String phone) {
        String send = "https://kejinlianmeng.com/api_v1/system/captcha/send";

        TreeMap params = new TreeMap();
        params.put("passport", phone);
        params.put("type", "exist");
        String s = new Date().getTime() / 1000 + "";
        params.put("timestamp", s);
        String nonce = nonce();
        params.put("nonce", nonce);

        String sign = sign(params);
        params.put("sign", sign);

        String cookie = getCookie(null);

        JSONObject jsonObject = new JSONObject(params);
        String s3 = jsonObject.toString();
        System.out.println(s3);
        String body = HttpRequest.post(send)
                .header("x-app-source", "pc")
                .header("x-os", "pc")
                .header("x-type", "user")
                .header("x-ver", "2.39.0")
                .header("cookie", cookie)
                .body(s3)
                .execute()
                .body();
        log.info("验证码发送结果={}", body);
    }

    /**
     * 获取nonce
     *
     * @return
     */
    private static String nonce() {

        //md5加密（1234567890-随机6位数+时间戳+api）
        String s11 = new Date().getTime() / 1000 + "";
        String s1 = "1234567890" + r() + s11 + "0" + "/api_v1/system/captcha/send";
        String nonce = DigestUtils.md5Hex(s1);
        return nonce;
    }

    /**
     * 获取sign
     *
     * @param params
     * @return
     */
    private static String sign(TreeMap params) {
        //"captcha=1111111,device_id=,device_type=web,guard=web,nonce=4bdb0fdf5e07ce2e1a8f39b3b318fb00,passport=18537003990,password=,timestamp=1726220281"
        //按照参数排序后  + md5加密 = str1
        //
        //str1+"pc"+"2.39.0"   = l
        //
        //f + l[1]+l[3]+l[7]+l[15]+h+l[31]
        //f = l的数字的第一个
        //h = l的字母的最后一个
        String cover = MapUntils.getCover(params).replace("&", ",");
        String substring = cover.substring(0, cover.length() - 1);
        System.out.println(substring);
        String first = DigestUtils.md5Hex(substring);
        String scend = DigestUtils.md5Hex(first + "");
        String s2 = scend + "pc" + "2.39.0";
        String l = DigestUtils.md5Hex(s2);
        Pattern p1 = Pattern.compile("\\d+");
        Matcher m1 = p1.matcher(l);
        StringBuffer num = new StringBuffer();
        while (m1.find()) {
            num.append(m1.group());
        }
        String f = num.substring(0, 1);
        // 正则表达式匹配任何字母字符
        String pattern = "[a-zA-Z]+";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(l);
        StringBuffer hstr = new StringBuffer();
        while (m.find()) {
            hstr.append(m.group());
        }
        String sign = f + l.substring(1, 2) + l.substring(3, 4) + l.substring(7, 8) + l.substring(15, 16) + hstr.substring(hstr.length() - 1, hstr.length()) + l.substring(l.length() - 1, l.length());
        return sign;
    }

    private static String r() {
        Random random = new Random();
        int min = 1000000;
        int max = 9999999;

        Integer randomNumber = random.nextInt(max - min + 1) + min;
        System.out.println("随机六位: " + randomNumber);
        return randomNumber.toString();
    }

    static String upLoadImg(String img,SalePartner salePartner) {
        String url = "https://kejinlianmeng.com/api_v1/system/upload/image";
        File file = null;
        try {
            BufferedImage image = ImageIO.read(new URL(img).openStream());
            byte[] bytes = ImgUntil.bufferedImageToByteArray(image);
            file = convert(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String body = HttpRequest.post(url).form("token", getTokenNew(salePartner).trim()).form("image", file).execute().body();
        return body;
    }

    public static File convert(byte[] byteArray) throws IOException {
        File file = File.createTempFile("kankantemp", ".jpg");
//        imgUrl = file.getPath();
        Path path = Paths.get(file.getAbsolutePath());
        try (FileOutputStream fos = new FileOutputStream(file)) {
            fos.write(byteArray);
        }catch (Exception e){

        }
        return file;
    }

    public static String getCover(Map<String, Object> params, List<GoodsInfoImg> infoImgs, String xiangqingtuId,SalePartner salePartner) {


        log.info("通过Map.keySet遍历key和value：");

        StringBuffer resut = new StringBuffer();

        for (String key : params.keySet()) {

            log.info("key= " + key + " and value= " + params.get(key));
            if (params.get(key).toString().contains("[")) {
                String o = params.get(key).toString();
                String[] split = o.replace("[", "").replace("]", "").split(",");
                for (String s : split) {
                    if (Objects.nonNull(params.get(key)) && StringUtils.isNotEmpty(s)) {
                        resut.append(key + "=" + s.trim() + "&");
                    }
                }
            } else {
                if (Objects.nonNull(params.get(key)) && StringUtils.isNotEmpty(String.valueOf(params.get(key)))) {
                    resut.append(key + "=" + params.get(key) + "&");
                }
            }

        }
        if (!CollectionUtils.isEmpty(infoImgs)) {
            for (GoodsInfoImg goodsInfoImg1 : infoImgs) {
                String s2 = upLoadImg(goodsInfoImg1.getImgUrl(),salePartner);
                String data2 = JSONObject.parseObject(s2).getString("data");
                String url2 = JSONObject.parseObject(data2).getString("url");
                Object o2 = JSONArray.parseArray(url2).get(0);
                resut.append("property[" + xiangqingtuId + "][]=" + o2 + "&");
            }
        }
        return resut.toString();
    }

}
